# -*- coding: utf-8 -*-

import sqlite3
import threading

class LocalDatabase:
    def __init__(self, db_name='local_db.db'):
        self.conn = sqlite3.connect(db_name, check_same_thread=False)
        self.cursor = self.conn.cursor()
        self.lock = threading.Lock()
        self._create_table()

    def _create_table(self):
        with self.lock:
            self.cursor.execute('''CREATE TABLE IF NOT EXISTS global_dict
                                  (name TEXT PRIMARY KEY, value TEXT)''')
            self.conn.commit()

    def set_value(self, name, value):
        with self.lock:
            self.cursor.execute("INSERT OR REPLACE INTO global_dict (name, value) VALUES (?, ?)", (name, str(value)))
            self.conn.commit()

    def get_value(self, name, defValue=None):
        with self.lock:
            self.cursor.execute("SELECT value FROM global_dict WHERE name=?", (name,))
            result = self.cursor.fetchone()
            if result:
                return eval(result[0])  # 使用eval将字符串转换回原来的类型
            else:
                return defValue

    def close(self):
        with self.lock:
            self.conn.close()



